<template>
  <el-dialog
    v-model="state.open"
    :title="state.title"
    :width="447"
    :before-close="cancel"
  >
    <el-form :model="state.formItem" :rules="state.rules" label-width="80px" ref="usersAddUpdateRef">
      <el-form-item label="商品名称" prop="name">
        <el-input v-model="state.formItem.name" placeholder="请输入商品名称"></el-input>
      </el-form-item>
      <el-form-item label="价格" prop="price">
        <el-input v-model="state.formItem.price" placeholder="请输入价格"></el-input>
      </el-form-item>
      <el-form-item label="描述" prop="desc">
        <el-input v-model="state.formItem.desc" placeholder="请输入描述"></el-input>
      </el-form-item>
      <el-form-item label="分类" prop="typeid">
        <el-select
          v-model="state.formItem.typeid"
          placeholder="请选择分类"
        >
          <el-option v-for="item in state.typeList" :key="item['typeid']" :value="item['typeid']" :label="item['name']"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="描述" prop="desc">
        <el-upload ref="uploadRef" :before-upload="handleUpload" action>
          <img v-if="state.imgUrl" :src="state.imgUrl" class="avatar" />
          <el-button v-else type="primary">上传图片</el-button>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <div style="text-align: center;">
        <el-button @click="cancel">关闭</el-button>
        <el-button type="primary" :loading="state.loading" @click="ok">提交</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts">
import { defineComponent, reactive, ref, unref, onMounted } from 'vue'
import { goodsAddOrUpdate } from '@/api/goods'
import { imgUpload } from '@/api/upload'
import { categoryPage } from '@/api/category'
import { baseURL } from '@/config/index'
import { ElMessage } from 'element-plus'
export default defineComponent({
  name: 'usersAddUpdate',
  emits:['reload'],
  setup(prop, context) {
    const usersAddUpdateRef = ref()
    const uploadRef = ref()
    // reactive定义多个数据的响应式
    const state = reactive<any>({
      open: false,
      title: "商品添加",
      loading: false,
      formItem: {
        name: '',
        price: '',
        desc: '',
        typeid: '',
        img: ''
      },
      rules: {
        name: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
        price: [{ required: true, message: "请输入价格", trigger: "blur" }],
        desc: [{ required: true, message: "请输入描述", trigger: "blur" }],
        typeid: [{ required: true, message: "请选择分类", trigger: "change" }],
      },
      typeList: [
        // { typeid: 33, name: "fenlei" },
        // { typeid: 2, name: "热菜" },
      ],
      imgUrl: ''
    })

    const cancel = () => {
      unref(usersAddUpdateRef).resetFields()
      state.open = false
      state.formItem = {
        name: '',
        price: '',
        desc: '',
        typeid: '',
        img: ''
      }
      state.imgUrl = ''
    }

    const ok = () => {
      unref(usersAddUpdateRef).validate((valid: boolean) => {
        if (!valid) return
        state.loading = true
        goodsAddOrUpdate(state.formItem)
          .then((res) => {
            state.loading = false
            if (res.data.code === 200) {
              ElMessage.success(state.title + '成功')
              context.emit('reload')
              cancel()
            } else {
              ElMessage.error(res.data.msg)
            }
          })
          .catch(() => {
            state.loading = false
          })
      })
    }

    const init = (params: any) => {
      if (params) {
        state.title = "商品修改";
        state.formItem = JSON.parse(JSON.stringify(params));
        state.imgUrl = params.img
      } else {
        state.title = "商品添加";
      }
      state.open = true;
    }

    const handleUpload = (file: any) => {
      if (file) {
        if (file.size > 500 * 1024) {
          ElMessage.error("图片尺寸太大");
          unref(uploadRef).clearFiles();
        } else {
          const reader = new FileReader();
          reader.readAsDataURL(file);
          reader.onload = () => {
            const _base64 = reader.result;
            state.imgUrl = _base64; //将_base64赋值给图片的src，实现图片预览
          };
          let formData = new FormData();
          formData.append("avatar", file);
          imgUpload(formData)
            .then((res) => {
              if (res.data.code === 200) {
                state.formItem.img = baseURL + res.data.imgUrl;
              } else {
                ElMessage.error(res.data.msg);
              }
            })
            .catch((err) => {
              ElMessage.error(err);
            });
          return false; //阻止图片继续上传，使得form表单提交时统一上传
        }
      }
      return false;
    }

    const getCategoryPage = () => {
      categoryPage({ pageNo: 1, pageSize: 9999 })
        .then(res => {
          state.typeList = res.data.data
        })
    }

    // 相当于原 mounted生命周期钩子函数
    onMounted(() => {
      getCategoryPage()
    })

    return {
      state,
      cancel,
      ok,
      usersAddUpdateRef,
      init,
      uploadRef,
      handleUpload,
      getCategoryPage
    }
  }
})
</script>
<style lang="less" scoped>
.avatar {
  width: 200px;
}
</style>
